package main

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"mxshop_srvs/goods_srv/global"
	"mxshop_srvs/goods_srv/model"
	"os"
	"strconv"
	"time"
)

type Conn struct {
	DB *gorm.DB
}

func NewConn() (*Conn, error) {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	dsn := "root:123456@tcp(127.0.0.1:3306)/mxshop_good_srv?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, //取消表名复数s
			//TablePrefix:   "mxshop_",
		},
		Logger: newLogger,
	})
	return &Conn{
		DB: db,
	}, err
}

func main() {
	conn, err := NewConn()
	if err != nil {
		log.Println("conn is error : ", err)
	}
	db := conn.DB

	_ = db.AutoMigrate(
		&model.Category{}, &model.Brands{}, &model.GoodsCategoryBrand{},
		&model.Goods{},
	)

	fmt.Println("sql 执行完成")
}

func test(DB gorm.DB) {
	var categoryBrandsList []model.GoodsCategoryBrand
	DB.Preload("Category").Preload("Brands").Find(&categoryBrandsList)
	//for _, v := range categoryBrandsList {
	//	fmt.Println(v.Brands, v.Category)
	//}
	var goodsList []model.Goods
	DB.Preload("Category").Preload("Brands").Find(&goodsList)
	for _, goods := range goodsList {
		fmt.Println("商品分类名称", goods.Category.Name)
	}
}

func MysqlToEs() {

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	dsn := "root:123456@tcp(127.0.0.1:3306)/mxshop_good_srv?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, //取消表名复数s
			//TablePrefix:   "mxshop_",
		},
		Logger: newLogger,
	})

	host := "http://10.26.10.121:9200"
	logger := log.New(os.Stdout, "mxshop", log.LstdFlags)
	global.EsClient, err = elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false),
		elastic.SetTraceLog(logger))
	if err != nil {
		panic(err)
	}
	var goodsList []model.Goods
	db.Find(&goodsList)
	for _, g := range goodsList {
		esGoods := model.EsGoods{
			ID:          g.ID,
			CategoryID:  g.CategoryID,
			BrandsID:    g.BrandsID,
			OnSale:      g.OnSale,
			ShipFree:    g.ShipFree,
			IsNew:       g.IsNew,
			IsHot:       g.IsHot,
			Name:        g.Name,
			ClickNum:    g.ClickNum,
			SoldNum:     g.SoldNum,
			FavNum:      g.FavNum,
			MarketPrice: g.MarketPrice,
			GoodsBrief:  g.GoodsBrief,
			ShopPrice:   g.ShopPrice,
		}
		_, err = global.EsClient.Index().Index(esGoods.GetIndexName()).BodyJson(esGoods).Id(strconv.Itoa(int(g.ID))).Do(context.Background())
		if err != nil {
			panic(err)
		}

	}
}
